// scaup
// (c) 2010, Normen Müller, normen.mueller@gmail.com  
// $Id: Strings.scala 97 2010-08-23 09:00:50Z normen.mueller $
package scaup.data

import scaup.PimpedType

import java.io.{ File, BufferedWriter, OutputStreamWriter, FileOutputStream }
import java.net.{URL, URI}
import java.security.MessageDigest

/** @thanks  Scalaz#StringW
 *  @author  <a href="mailto:normen.mueller@googlemail.com">Normen M&#xFC;ller</a>
 *  @version 0.0.6
 */
sealed trait StringW extends PimpedType[String] {
  lazy val s = value

  lazy val toFile = new File(s)

  lazy val toURL = new URL(s)
  
  lazy val toURI = new URI(s)

  lazy val toMD5 = ((md: MessageDigest) => try {    
    md.update(s.getBytes)
    md.digest().map(0xFF & _).map{ "%02x".format(_) }.mkString
  } catch { case ex@_ => error(ex.getMessage) })(MessageDigest.getInstance("MD5"))

  def splitAt(index: Int) =
    if (index < 0) ("", s)
    else if (index >= s.length) (s, "")
    else (s.substring(0, index), s.substring(index + 1))

  def >>>(file: File) = ((out: BufferedWriter) => try {
    out.write(s)
    out.close()
    file
  } catch {
    case ex@_ => error(ex.getMessage)
  })(new BufferedWriter(new OutputStreamWriter(new java.io.FileOutputStream(file), "UTF8")))
  
  def diff(that: String) = scaup.text.Differ.diff(value, that)
}

/** @thanks  Scalaz#Strings
 *  @author  <a href="mailto:normen.mueller@googlemail.com">Normen M&#xFC;ller</a>
 *  @version 0.0.6
 */
trait Strings {
  implicit def StringTo(ss: String): StringW = new StringW {
    val value = ss
  }
}
